// pages/MineInfoPage/MineInfoPage.js
var api = require("../../utils/request.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    leaderId:'',
    resultData:{},
    isUploadAvatar:false,
    userNickname:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    that.data.leaderId = options.leaderId;
    that.setData({
      navheight:getApp().globalData.zHeight*2+50,
      hideUplooadModal:true
    })
  },
  gotoAllOrder(){
    wx.navigateTo({
      url: '/pages/MyOrderRecordPage/MyOrderRecordPage?leaderId='+this.data.leaderId
    });
  },
  seleTypeOrder:function(e){
    var index = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/MyOrderRecordPage/MyOrderRecordPage?leaderId='+this.data.leaderId+'&index='+index
    });
  },

  gotoCheckInScore(){
    console.log('dddd=='+this.data.leaderId)
    wx.navigateTo({
      url: '/pages/CheckInScorePage/CheckInScorePage?leaderId='+this.data.leaderId
    });
  },
  gotoMyBalance(){
    wx.navigateTo({
      url: '/pages/MyBalancePage/MyBalancePage?leaderId='+this.data.leaderId
    });
  },
  gotoCoupon(){
    wx.navigateTo({
      url: '/pages/CouponListPage/CouponListPage?leaderId='+this.data.leaderId
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.makeMyInfo()
  },

  makeMyInfo(){
    var that = this
    api.request1({"leaderId":that.data.leaderId, "path": "user/mineInfo","token":wx.getStorageSync('token')}, function (result) {
      if(result.code=='0'){
        that.data.resultData = result.data;
        if(result.data.phone.length!=0){
           var p1 = result.data.phone.substr(0,3)
           var p2 = result.data.phone.substr(7,4)
           result.data.phone = p1+'****'+p2;
        }
        that.setData({
          balance:result.data.balance,
          phone:result.data.phone,
          nickName:(result.data.nickName.length==0||result.data.nickName=='微信用户')?'未登录':result.data.nickName,
          headUrl:result.data.headUrl,
          bonus:result.data.bonus,
          signBonus:result.data.signBonus,
          signNum:result.data.signNum
        })
      }  
    }, function (error) {
      console.log('error==')
    })
  },
  getrealtimephonenumber (e) {
    var that = this
    console.log(e.detail.code)  // 动态令牌
    console.log(e.detail.errMsg) // 回调信息（成功失败都会返回）
    console.log(e.detail.errno)  // 错误码（失败时返回）
    if(e.detail.errno == 103){

    }else{
      if(e.detail.code!=undefined){
        api.request1({"code":e.detail.code, "path": "user/getUserPhone","token":wx.getStorageSync('token')}, function (result) {
           if(result.code=='0'){
            wx.setStorageSync('phone', result.msg)
            if(result.msg.length!=0){
              var p1 = result.msg.substr(0,3)
              var p2 = result.msg.substr(7,4)
              that.setData({
                phone:p1+'****'+p2,
              })  
           }
          }
          }, function (error) {
          })
      }
    }
  },

  getMineInfo(){
    var that = this
    console.log('e333')
    if(that.data.resultData.headUrl.indexOf('txeimg.llmmwl.com/leaderHeadImg/random') ==-1){
      var animation = wx.createAnimation({
        duration: 200,//动画的持续时间 默认400ms 数值越大，动画越慢 数值越小，动画越快
        timingFunction: 'ease',//动画的效果 默认值是linear
        })
        this.animation = animation 
        setTimeout(function(){
        that.fadeIn();//调用显示动画
        },10) 
        console.log('e333')
        that.setData({
          hideUplooadModal:false,
          animationData: that.animation.export(),
          avatarUrl:that.data.resultData.headUrl
        })
  
    }
  },
  //动画集
  fadeIn:function(){
    this.animation.translateY(0).step()
    this.setData({
    animationData: this.animation.export()//动画实例的export方法导出动画数据传递给组件的animation属性
    }) 
    },
  fadeDown:function(){
    this.animation.translateY(500).step()
    this.setData({
    animationData: this.animation.export(), 
    })
  },
  closeUploadImg:function(){
    var that = this
    var animation = wx.createAnimation({
      duration: 200,//动画的持续时间 默认400ms 数值越大，动画越慢 数值越小，动画越快
      timingFunction: 'ease',//动画的效果 默认值是linear
      })
      this.animation = animation 
      setTimeout(function(){
      that.fadeDown();//调用显示动画
      },10) 
      that.setData({
        hideUplooadModal:true,
        animationData: that.animation.export()
      })
  },
  onChooseAvatar(e){
    const { avatarUrl } = e.detail 
    this.setData({
      avatarUrl,
    })
    this.getOSS(avatarUrl)
  },
  getOSS:function(avatarUrl){
    var that = this
    api.request1({"path": "user/getOSS","token":wx.getStorageSync('token')}, function (result) {
      if(result.code=='0'){
        //host,signature,policy,accessId,dir, path
         that.uploadImg(result.data.host,result.data.signature,result.data.policy,result.data.accessId,result.data.dir,avatarUrl);
       } else if(result.code == '301'){
         wx.showModal({
           title: '提示',
           content: result.msg,
           showCancel:false,
           confirmText:'我知道了',
           complete: (res) => {
 
             if (res.confirm) {
               
             }
           }
         })
       }
     }, function (error) {
     })
  },
  uploadImg:function(host1,signature1,policy1,accessId1,dir1, path){
    var that = this
    const host = host1;
    const signature = signature1;
    const ossAccessKeyId = accessId1;
    const policy = policy1;
    var imgName = new Date().getTime() + '.png';
    const key = dir1+ imgName;
    //console.log(key)
    const securityToken = ''; 
    const filePath = path; // 待上传文件的文件路径。
    wx.uploadFile({
      url: host, // 开发者服务器的URL。
      filePath: filePath,
      name: 'file', // 必须填file。
      formData: {
        key,
        policy,
        OSSAccessKeyId: ossAccessKeyId,
        signature,
        // 'x-oss-security-token': securityToken // 使用STS签名时必传。
      },
      success: (res) => {
        //console.log('msg='+res.errMsg+',code='+res.statusCode);
        if (res.statusCode === 204) {
          //console.log('上传成功');
          api.request1({"imgName":imgName,"path": "user/updateUserHeadImg","token":wx.getStorageSync('token')}, function (result) {
            if(result.code=='0'){
              that.data.isUploadAvatar = true
              that.makeMyInfo();
              wx.setStorageSync('avatarUrl', result.msg)
             } else if(result.code == '301'){
               wx.showModal({
                 title: '提示',
                 content: result.msg,
                 showCancel:false,
                 confirmText:'我知道了',
                 complete: (res) => {
       
                   if (res.confirm) {
                     
                   }
                 }
               })
             }
           }, function (error) {
           })
        }
      },
      fail: err => {
        //console.log(err);
      }
    });
  },
  submit: function(){
    var that = this

    if(that.data.userNickname.length==0){
      wx.showToast({
        title: '请输入昵称',
        icon:"error"
      })
      return
    }

    api.request1({"nickName":that.data.userNickname, "path": "user/updateUserName","token":wx.getStorageSync('token')}, function (result) {

       if(result.code=='0'){
          that.closeUploadImg();
          that.makeMyInfo();
          setTimeout(() => {
            wx.showToast({
              title: '设置成功',
            })
          }, 1);
   

          wx.setStorageSync('nickName', that.data.userNickname)
        } else if(result.code == '301'){
          wx.showModal({
            title: '提示',
            content: result.msg,
            showCancel:false,
            confirmText:'我知道了',
            complete: (res) => {
  
              if (res.confirm) {
                
              }
            }
          })
        }else{
        }
      }, function (error) {
      })

  },
  getName(e) {
    this.data.userNickname = e.detail.value;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  handlerGobackClick() {
    wx.navigateBack({
      delta: 1
    });
  }
})